import {createContext, Dispatch, Reducer, useContext, useReducer} from 'react'

export type Task = {
  id: number,
  text: string,
  done: boolean
}

interface Props {
  children?: any
}

export type Action = {
  type: string,
  [key: string]: any
}

const initialTasks = [
  { id: 0, text: 'Philosopher’s Path', done: true },
  { id: 1, text: 'Visit the temple', done: false },
  { id: 2, text: 'Drink matcha', done: false }
];

export const TasksContext = createContext(initialTasks)

const DispatchContext = createContext<Dispatch<Action>>(null as any)

const reducer: Reducer<Task[], Action> = (tasks, action) => {
  if (action.type == 'added') {
    return [
      ...tasks, {
        id: action.id,
        text: action.text,
        done: false
      }
    ]
  }

  if (action.type == 'changed') {
    return tasks.map(t => {
      if (t.id == action.task.id) {
        return action.task
      }
      return t
    })
  }

  if (action.type == 'deleted') {
    return tasks.filter(t => t.id !== action.id)
  }

  return tasks
}

export function Provider({children}: Props) {
  const [tasks, dispatch] = useReducer(reducer, initialTasks)

  return (
    <TasksContext.Provider value={tasks}>
      <DispatchContext.Provider value={dispatch}>
        {children}
      </DispatchContext.Provider>
    </TasksContext.Provider>
  )
}

export function useTasks() {
  return useContext(TasksContext)
}

export function useDispatch() {
  return useContext(DispatchContext)
}